package com.example.demo.leetcode;

public interface _25_K个一组反转链表 {

    public static void main(String[] args) {
        ListNode listNode = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
        ListNode listNode1 = reverseKGroup(listNode, 2);
        System.out.println();
    }

    public static ListNode reverseKGroup(ListNode head, int k) {
        ListNode temp = new ListNode(-1, head);
        ListNode listNode = head;
        int i = 0;
        while (head != null) {
            head = head.next;
            i++;
            if (i == k) {
                reverse(listNode, head, k);
                listNode = head;
            }
        }
        return temp.next;
    }

    public static void reverse(ListNode head, ListNode tail, int k) {
        ListNode pre = new ListNode(-1, tail);
        int i = 0;
        while (head != null) {
            pre.next = new ListNode(head.val, pre.next);
            head = head.next;
            i++;
            if (i == k) {
                break;
            }
        }
        head = pre.next;
    }
}
